<template>
  <div class="nav_outer">
    <Header>实名认证</Header>
    <div class="content">
      <div class="upload" v-if="isInapp">
        <div class="upload_item" @click="uploadImg(1)">
          <img :src="uinfo.cardPicFront | imgpre" v-if="uinfo.cardPicFront" class="cardpic">
          <img src="../assets/img/veriprev@2x.png" v-else>
        </div>
        <div class="upload_item" @click="uploadImg(2)">
          <img :src="uinfo.cardPicBack | imgpre" v-if="uinfo.cardPicBack" class="cardpic">
          <img src="../assets/img/veriback@2x.png" v-else>
        </div>
      </div>
      <div class="upload" v-if="!isInapp">
        <div class="upload_item">
          <img :src="uinfo.cardPicFront | imgpre" v-if="uinfo.cardPicFront" class="cardpic">
          <img src="../assets/img/veriprev@2x.png" v-else>
          <input type="file" class="upload_input" ref="File1" multiple="false" accept="image/*" @change="changeImage($event,1)"/>
        </div>
        <div class="upload_item">
          <img :src="uinfo.cardPicBack | imgpre" v-if="uinfo.cardPicBack" class="cardpic">
          <img src="../assets/img/veriback@2x.png" v-else>
          <input type="file" class="upload_input" ref="File2" multiple="false" accept="image/*" @change="changeImage($event,2)"/>
        </div>
      </div>
      <div class="inputarea">
        <div class="flex_bet">
          <span>真实姓名</span>
          <div>
            <input type="text" name="name" v-model="uinfo.name">
          </div>
        </div>
        <div class="flex_bet">
          <span>身份证号</span>
          <div>
            <input type="text" name="name" v-model="uinfo.cardNo">
          </div>
          
        </div>
      </div>
      <div class="btn_save" @click="save">提交</div>
    </div>
  </div>
</template>

<script>
import Header from '@/components/commonComponents/Header'
export default {
  data() {
    return {
      uinfo:{
        name: '',
        cardNo: '',
        cardPicBack: '',
        cardPicFront: ''
      },
      isInapp: this.app.isInAPP
    }
  },
  created(){
    let user = this.$store.state.user;
    this.uinfo.cardPicFront = user.cardPicFront;
    this.uinfo.cardPicBack = user.cardPicBack;
    this.uinfo.name = user.name;
    this.uinfo.cardNo = user.cardNo;
    this.uinfo.id = user.id;
  },
  methods: {
    navito(url){
      this.$router.push({path:url}); 
    },
    uploadImg(type){
      let that = this;
      this.app.scanIdcard(type).then((res)=>{
        let data = JSON.parse(res);
        if(type==1 && data.idNumber){
          that.uinfo.cardNo = data.idNumber;
          that.uinfo.name = data.name;
          that.uinfo.genderName = data.gender;
          that.uinfo.gender = data.gender=='男'? 1: 2;
          that.uinfo.birth = data.birthday.substr(0,4)+'-'+data.birthday.substr(4,2)+'-'+data.birthday.substr(-2,2)+' 00:00:00';
          that.uinfo.nation = data.ethnic;
          that.uinfo.cardPicFront = data.cardPicFront;
        }else if(type==2 && data.signDate){
          that.uinfo.cardPicBack = data.cardPicBack;
        }
      })
    },
    changeImage (e,type) {
      let that = this;
      let files = e.target.files || e.dataTransfer.files
      if (!files.length) return
      this.$loading('上传中..');
      this.imgPreview(files[0],type);
      
    },
    uploadFile(file,type){
      let that = this;
      this.Http.orginupload(file).then((res)=>{
        that.$loading.close();
        if(type==1){
          that.uinfo.cardPicFront = res;
          let imgurl=that.Http.imgpre+res;
          that.shibie(imgurl,type);
          that.$refs.File1.value = '';
        }else if(type==2){
          that.uinfo.cardPicBack = res;
          that.$refs.File2.value = '';
        }
      },err=>{
        that.$loading.close();
        that.$refs['File'+type].value = '';
        that.$toast('上传失败');
      })
    },
    imgPreview (file,type) {
      let self = this
      let reader = new FileReader()
        // 将图片2将转成 base64 格式
      reader.readAsDataURL(file)
        // 读取成功后的回调
      reader.onloadend = function () {
        let result = this.result
        let img = new Image()
        img.src = result
          // 判断图片是否小于900K,是就直接上传，反之压缩图片
        if (this.result.length <= (800 * 1024)) {
          let file1 = self.dataURLtoFile(this.result)
          self.uploadFile(file1,type)
        } else {
          img.onload = function () {
            let data = self.compress(img)
            self.bannerUrl = data
            let file1 = self.dataURLtoFile(data)
            self.uploadFile(file1,type)
          }
        }
      }
    },
    dataURLtoFile (dataUrl) { // base64转file
      const filename = `img${Date.now()}`
      const arr = dataUrl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const suffix = mime.split('/')[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename + '.' + suffix, { type: mime })
    },
    compress (img) {
      let canvas = document.createElement('canvas')
      let ctx = canvas.getContext('2d')
      // 瓦片canvas
      let tCanvas = document.createElement('canvas')
      let tctx = tCanvas.getContext('2d')
      let initSize = img.src.length
      let width = img.width
      let height = img.height
      // 如果图片大于四百万像素，计算压缩比并将大小压至400万以下
      let ratio
      if ((ratio = width * height / 4000000) > 1) {
        ratio = Math.sqrt(ratio)
        width /= ratio
        height /= ratio
      } else {
        ratio = 1
      }
      canvas.width = width
      canvas.height = height
      // 铺底色
      ctx.fillStyle = '#fff'
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      // 如果图片像素大于100万则使用瓦片绘制
      let count
      if ((count = width * height / 1000000) > 1) {
        console.log('超过100W像素')
        count = ~~(Math.sqrt(count) + 1) // 计算要分成多少块瓦片
      // 计算每块瓦片的宽和高
        let nw = ~~(width / count)
        let nh = ~~(height / count)
        tCanvas.width = nw
        tCanvas.height = nh
        for (let i = 0; i < count; i++) {
          for (let j = 0; j < count; j++) {
            tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh)
            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh)
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height)
      }
      // 进行最小压缩
      let ndata = canvas.toDataURL('image/jpeg', 0.8)
      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0
      return ndata
    },
    shibie(url,type){
      //this.$loading('识别中..');
      this.Http2.put(`/mobile/weixinIdCard/getIdInfo`,{
        imageUrl: url
      }).then(res => {
        if(res.errmsg=='ok'){
          if(type==1){
            this.uinfo.cardNo = res.id;
            this.uinfo.name = res.name;
            this.uinfo.genderName = res.gender;
            this.uinfo.gender = res.gender=='男'? 1: 2;
            this.uinfo.birth = res.birthday.substr(0,4)+'-'+res.birthday.substr(4,2)+'-'+res.birthday.substr(6,2);
            this.uinfo.nation = res.nationality;
          }
        }
        this.$loading.close();
      },err=>{
        this.$loading.close();
      });
    },
    loadUser() {
      this.Http.get("/yzj/current-customer", null).then(res => {
        this.$store.commit('SETUSER', res);
        localStorage.removeItem("user");
        localStorage.setItem("user",JSON.stringify(res));
      });
    },
    save(){
      if(!this.uinfo.cardNo || !this.uinfo.name || !this.uinfo.cardPicFront || !this.uinfo.cardPicBack){
        this.$toast('信息输入不完整');
        return
      }
      this.Http.put("/yzj/personal/app/customerAuth",this.uinfo).then(res => {
        this.loadUser();
        this.$router.back();
      });
    }
  },
  components: {
    Header
  }
}
</script>

<style scoped lang='scss'>
  @function px2em($px) {
      @if (unitless($px)) {
      @return px2em($px + 0px);
      } @else if (unit($px) == em) {
      @return $px;
      }
      @return ($px / 75px) * 1rem;
  }
  .content{
    color: #333;
  }
  body{
    background: #F5F5F5!important;
  }
  .upload{
    overflow: hidden;
    text-align: center;
    margin: px2em(16);
    background-color: #fff;
    .upload_item{
      width: 50%;
      height: 4rem;
      padding: .55rem 0;
      box-sizing: border-box;
      float: left;
      position: relative;
      overflow: hidden;
      >img{
        width: px2em(234);
        margin: 0;
      }
    }
    .upload_input{
      position: absolute;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      opacity: 0;
    }
  }
  .inputarea{
    margin-top: px2em(20);
    &>div{
      padding: 0 px2em(30);
      margin-top: 5px;
      background: #fff;
    }
    input{
      text-align: right;
      padding-right: 0;
    }
  }
  .btn_save{
    height: px2em(80);
    line-height: px2em(80);
    border-radius: px2em(40);
    text-align: center;
    background: #317ee4;
    color: #fff;
    margin: px2em(30);
  }
</style>
